//
//  ViewController.m
//  FastContact
//
//  Created by William Cai on 15/4/17.
//  Copyright (c) 2015年 William Cai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

//create default values (MUST REWRITE)
NSString *messageBody = @"Message Body";
NSString *messageSubject = @"Message subject";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.numberField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.emailField];

}

- (void)textChange {
    self.sendmessageButton.enabled =(self.numberField.text.length);
    self.sendemailButton.enabled =(self.emailField.text.length);
}

- (IBAction)sendmessageAction:(id)sender {
    //get phone number from input
    NSString *phone = self.numberField.text;
    
    //try validate phone number
    if ([self validatePhone:phone] == NO) {
        [self makeAlert:@"请输入正确的手机号"];
        //set responder to this text input
        [self.numberField becomeFirstResponder];
        
        return;
        
    }else{
        //test if this device can send message
        if([MFMessageComposeViewController canSendText] ){
            //create new instance from MFMessageComposeViewController
            MFMessageComposeViewController* comp = [[MFMessageComposeViewController alloc] init];
            
            //set properties
            NSString *messageBody = [NSString stringWithFormat:@"我是xxx，请帮我打急救电话"];
            comp.body = messageBody;
            comp.recipients = @[self.numberField.text];
            comp.messageComposeDelegate = self;
            
            //present view controller
            [self presentViewController:comp animated:YES completion:nil];
        }
        else{
            [self makeAlert:@"此设备无法发送短信"];
        }
    }
}

- (IBAction)sendemailAction:(id)sender {
    //get email address from text input
    NSString *email = self.emailField.text;
    
    //try validate email
    if ([self validateEmail:email] == NO) {
        [self makeAlert:@"请输入正确的邮件地址"];
        //set responder to this text input
        [self.emailField becomeFirstResponder];
        
        return;
    }else{
        //create new instane of MFMailComposeViewController
        MFMailComposeViewController* mc = [[MFMailComposeViewController alloc] init];
        //set delegate
        mc.mailComposeDelegate = self;
        
        //set message body
        [mc setMessageBody:@"我是xxx，请帮我打急救电话" isHTML:NO];
        
        //set message subject
        [mc setSubject:@"求救信"];
        
        //set message recipients
        [mc setToRecipients:[NSArray arrayWithObject:self.emailField.text]];
        
        //open dialog
        [self presentViewController:mc animated:YES completion:nil];
    }

}

#pragma mark - sms composer delegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    //test result
    switch (result) {
        case MessageComposeResultCancelled:
            [self makeAlert:@"操作取消"];
            break;
            //message was sent
        case MessageComposeResultSent:
            [self makeAlert:@"发送成功"];
            break;
        case MessageComposeResultFailed:
            [self makeAlert:@"发送失败"];
            break;
        default:
            break;
    }
    //dismiss view
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - mail composer delegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    
    //if result is possible
    if(result == MFMailComposeResultSent || result == MFMailComposeResultSaved || result == MFMailComposeResultCancelled){
        
        //test result and show alert
        switch (result) {
            case MFMailComposeResultCancelled:
                [self makeAlert:@"操作取消"];
                break;
            case MFMailComposeResultSaved:
                [self makeAlert:@"操作已保存"];
                break;
                //message was sent
            case MFMailComposeResultSent:
                [self makeAlert:@"发送成功"];
                break;
            case MFMailComposeResultFailed:
                [self makeAlert:@"发送失败"];
                break;
            default:
                break;
        }
    }
    //else exists error
    else if(error != nil){
        //show error
        [self makeAlert:[error localizedDescription]];
    }
    //dismiss view
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - check for vaild

//make alert from nsstring
-(void)makeAlert:(NSString *)message{
    [[[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}

//Validate email address
- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:candidate];
}

//Validate phone number
-(BOOL)validatePhone : (NSString *)phoneNumber{
    NSString *phoneRegex = @"[0-9]+";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    return [test evaluateWithObject:phoneNumber];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end